package com.beta.restapi.controller.upload;

import com.beta.common.exception.ControllerException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by vector on 2017/1/12.
 */
@Component
public abstract class AbstractImageHandler {

    @Value("${assets.path}")
    private String assetsPath;

    public String saveImage(MultipartFile multipartFile, HttpServletRequest request, Integer userId) {
        String fileName = uuidFileName(multipartFile);
        String relativePathToSave = buildRelativePathForSave(request, userId, fileName);
        File fileToStore = new File(assetsPath, relativePathToSave);
        if (!fileToStore.exists()) {
            fileToStore.mkdirs();
        }
        try {
            beforeImageSave(request, userId, fileName);
            multipartFile.transferTo(fileToStore);
            afterImageSave(request, userId, fileName);
            return relativePathToSave;
        } catch (IOException e) {
            throw new ControllerException("E90001");
        }
    }

    public void deleteImage(HttpServletRequest request, Integer userId) {
        String imageRelativePath = buildImageRelativePathForDelete(request, userId);
        beforeImageDelete(request, userId);
        File imageFile = new File(assetsPath, imageRelativePath);
        if (imageFile.exists()) {
            FileUtils.deleteQuietly(imageFile);
        }
        afterImageDelete(request, userId);
    }

    protected abstract String buildRelativePathForSave(HttpServletRequest request, Integer userId, String fileName);

    protected abstract String buildImageRelativePathForDelete(HttpServletRequest request, Integer userId);

    protected void beforeImageSave(HttpServletRequest request, Integer userId, String fileName) {
        // adapter method
    }

    protected void afterImageSave(HttpServletRequest request, Integer userId, String fileName) {
        // adapter method
    }

    protected void beforeImageDelete(HttpServletRequest request, Integer userId) {
        // adapter method
    }

    protected void afterImageDelete(HttpServletRequest request, Integer userId) {
        // adapter method
    }

    protected String uuidFileName(MultipartFile multipartFile) {
        String originalFilename = multipartFile.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        return String.join(".", UUID.randomUUID().toString(), extension);
    }

}
